package cn.machen.www.fashion.dao;

import cn.itcast.jdbc.TxQueryRunner;
import cn.machen.www.fashion.pojo.User;
import cn.machen.www.fashion.utils.JDBCUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    QueryRunner queryRunner = new TxQueryRunner();

    //根据username查找用户
    public User findByUsername(String username) {
        User user =null;
        try {
            String sql = "select * from tb_user where username=?";
            user = queryRunner.query(sql, new BeanHandler<User>(User.class), username);
        } catch (SQLException e) {
            throw new RuntimeException();
        }
        return user;
    }
    //根据email查找用户
    public User findByUserEmail(String email){
        User user =null;
        String sql = "select * from tb_user where email=?";
        try {
            user = queryRunner.query(sql,new BeanHandler<User>(User.class),email);
        } catch (SQLException e) {
            throw new RuntimeException();
        }
        return user;

    }

    //添加用户
    public void add(User user){
        try {
            String sql = "insert into tb_user values(?,?,?,?,?,?)";    //用户状态默认为0（未激活）
            Object parm[] = {user.getUid(),user.getUsername(),user.getPassword(),user.getEmail(),0,user.getActivecode()};
            queryRunner.update(sql,parm);
        } catch (SQLException e) {
            throw new RuntimeException();
        }
    }

    //查找用户
    public User findByCode(String code)  {
        User user =null;
        String sql = "select * from tb_user where activecode=?";
        try {
            return  queryRunner.query(sql, new BeanHandler<User>(User.class), code);
        } catch (SQLException e) {
            throw new RuntimeException();
        }
    }
    //修改用户的状态
    public void updataStatus(int uid,String code){
        String sql = "update tb_user set state=? where uid=?";
        try {
            queryRunner.update(sql,uid,code);
        } catch (SQLException e) {
            throw new RuntimeException();
        }

    }

}
